#ifndef __HTTP_SERVER_H__
#define __HTTP_SERVER_H__

#include<iostream>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<string>
#include<signal.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#define BACKLOG 5
using namespace std;
class HttpServer{
private:
    int port;
    int lsock;
public:
    HttpServer(int _port = 8080):port(_port),lsock(-1)
    {}
    void initServer(){
        //设置SIGCHLD的默认递达方式为忽略
        signal(SIGCHLD,SIG_IGN);
        //创建监听套接字
        lsock = socket(AF_INET,SOCK_STREAM,0);
        if(lsock < 0){
            cerr<<"sock error"<<endl;
            exit(2);
        }
        //填充协议族/ip/端口号到sockaddr_in
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        
        // 使用setsockopt 设置 socket 描述符的选项 SO_REUSEADDR 为 1，表示允许创建 端口号相同但IP地址不同的多个socket描述符
        // 解决 服务器TIME_WAIT 导致的重启服务器进而发生绑定失败的问题
        int opt = 1;
        setsockopt(lsock,SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

        //绑定端口号
        if(bind(lsock,(struct sockaddr*)&local,sizeof(local)) < 0){
            cerr<<"bind error"<<endl;
            exit(3);
        }
        //开始监听
        if(listen(lsock,BACKLOG) < 0 ){
            cerr<<"listen error"<<endl;
            exit(4);
        }
    }
    void Start(){
        cout << "HttpServer start"<<endl;
        struct sockaddr_in peer;
        while(true){
            socklen_t len = sizeof(peer);
            int sock = accept(lsock,(struct sockaddr*)&peer,&len);
            if(sock < 0){
                cerr << "accept error" <<endl;
                continue;
            }
            cout<< "Get a new link"<<endl;
            if(fork() == 0){
                close(lsock);
                EchoHttp(sock);
                exit(0);
            }
            close(sock);
        }       
    }
    void EchoHttp(int sock){
        char request[2048];
        ssize_t s =recv(sock,&request,sizeof(request)-1,0);
        if(s > 0){
            request[s] = 0;
            cout << request <<endl; 

            string response = "HTTP/1.0 200 OK \r\n";
            response += "Client-type : text/html\r\n";
            response += "\r\n";
            response += "\
                         <!DOCTYPE html>\
                         <html>\
                         <head>\
                         <title>HTTPTEST</title>\
                         </head>\
                         <body>\
                         <h1>HTTP TEST</h1>\
                         <p>Hello World!</p>\
                         </body>\
                         </html>\
                          ";
            send(sock,response.c_str(),response.size(),0);
        }
        close(sock);
    }
    ~HttpServer(){
        if(lsock != -1){
            close(lsock);
        }
    }
};
#endif
